
module uart2(
    input clk,
    input in,
    input reset,    // Synchronous reset
    output reg [7:0] out_byte,
    output reg done
); //
	parameter IDLE = 4'd0, DATA = 4'd1, STOP = 4'd2, ERR = 4'd3;
    
    reg [3:0] current_state, next_state;
    reg [7:0] buffer;
    reg [3:0] counter;
    
    always @(posedge clk) begin
        if (reset)
            current_state <= IDLE;
        else begin
            current_state <= next_state;
        end
    end
    
    always @(*) begin
        next_state = current_state;
        case (current_state)
            IDLE: if (in == 1'b0) next_state = DATA;
            DATA: if (counter == 4'd7) next_state = STOP;
            STOP: next_state = (in == 1'b1) ? IDLE : ERR;
            ERR: if (in == 1'b1) next_state = IDLE;
            default: next_state = IDLE;
        endcase
    end
    
    always @(posedge clk) begin
        case (current_state)
            IDLE: begin
                out_byte <= 8'd0;
                buffer <= 8'd0;
                counter <= 4'd0;
                done <= 1'b0;
            end
            DATA: begin
                if (counter < 8) begin
                    buffer <= { in, buffer[7:1] };
                    counter <= counter + 1'b1; 
                end
            end
            STOP: begin
                if (next_state == IDLE) begin
                    out_byte <= buffer;
                    done <= 1'b1;
                end
            end
        endcase
    end

endmodule

